
# ========================= imports =========================
from datetime import datetime, timedelta
from funcs.constants import _LEAP_SECONDS
# ===========================================================

# ======================================================================
class GPST:
    def __init__(self,week=None,day=None,second=None,microsecond=None):
        self.week=week
        self.day=day
        self.second=second
        self.ms=microsecond
# ======================================================================

#--------------------------------------------------------------------------
#----------------UTC时间(年月日时分秒)转GPS周和周内秒-----------------------
#----------------输入:UTC时间(datetime类型)---------------------------------
#----------------输出:GPS周、周内日、周内秒、毫秒---------------------------
#--------------------------------------------------------------------------
def utc2Gpst(utc, leapseconds=_LEAP_SECONDS):
    datetimeformat = "%Y-%m-%d %H:%M:%S.%f"
    epoch = datetime.strptime("1980-01-06 00:00:00.000", datetimeformat)
    tdiff = utc - epoch + timedelta(seconds=leapseconds)
    gpsweek = tdiff.days // 7
    gpsday = tdiff.days - 7*gpsweek
    gpssecond = tdiff.seconds + 86400*(tdiff.days -7*gpsweek)
    gpsmicrosecond=tdiff.microseconds
    return GPST(gpsweek,gpsday,gpssecond,gpsmicrosecond)


#------------------------------------------------------------------------------
#----------------输入：GPS周、GPS周内秒、闰秒-------------------------------------
#----------------输出：UTC时间（格林尼治时间）------------------------------------
#----------------输入示例:gpst2Utc(2119, 214365.000)----------------------------
#----------------输出示例： '2020-08-18 11:32:27.000000'-------------------------
#-------------------------------------------------------------------------------
def gpst2Utc(gpsweek, gpssecond, leapseconds=_LEAP_SECONDS):
    datetimeformat = "%Y-%m-%d %H:%M:%S.%f"
    epoch = datetime.strptime("1980-01-06 00:00:00.00", datetimeformat)
    # timedelta函数可处理seconds为负数的情况
    elapsed = timedelta(days=(gpsweek*7), seconds=(gpssecond-leapseconds))
    return epoch+elapsed